from fastapi import FastAPI, Request, Response
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.middleware.cors import CORSMiddleware
import uvicorn

app = FastAPI(
    title="FastAPI学习项目",
    description="这是一个用于学习FastAPI的示例项目",
    version="1.0.0",
    docs_url=None,  # 禁用默认的swagger文档
    redoc_url="/redoc"
)

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

# 中间件运行顺序
'''
m1 request--------------------------------
请求路径: /hello
请求方法: GET
客户端IP: 127.0.0.1
m2 request--------------------------------
请求路径: /hello
请求方法: GET
客户端IP: 127.0.0.1
m2 response--------------------------------
<starlette.middleware.base._StreamingResponse object at 0x0000000005F77B60>
m1 response--------------------------------
<starlette.middleware.base._StreamingResponse object at 0x0000000005FC07D0>
'''

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.middleware("http")
async def m2(request: Request, call_next):
    print("m2 request--------------------------------")
    print(f"请求路径: {request.url.path}")
    print(f"请求方法: {request.method}")
    print(f"客户端IP: {request.client.host}")
    response = await call_next(request)
    print("m2 response--------------------------------")
    response.headers["X-CORS-TEST"] = "m2"
    print(response)
    return response

@app.middleware("http")
async def m1(request: Request, call_next):
    print("m1 request--------------------------------")
    print(f"请求路径: {request.url.path}")
    print(f"请求方法: {request.method}")
    print(f"客户端IP: {request.client.host}")
    if request.client.host in ["127.0.0.1", "localhost"] and request.url.path == "/hello": # 禁止本地访问示例
        return Response(status_code=403,content="禁止本地访问")
    
    response = await call_next(request)
    print("m1 response--------------------------------")
    print(response)
    return response

@app.get("/",
    tags=["根路径"],

    summary="根路径访问",
    description="这是网站的根路径，返回一个简单的欢迎消息",
    response_description="返回包含欢迎消息的JSON对象"
)

@app.get("/docs", include_in_schema=False)
async def custom_swagger_ui_html():
    return get_swagger_ui_html(
        openapi_url=app.openapi_url,
        title=app.title + " - Swagger UI",
        oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
        swagger_js_url="/static/swagger-ui-bundle.js",
        swagger_css_url="/static/swagger-ui.css",
    )

@app.get("/hello")
async def hello():
    return {"message": "Hello, World!"}


if __name__ == "__main__":
    uvicorn.run(
        "main_cors:app", 
        host="127.0.0.1", 
        port=8000, 
        reload=True,
        log_level="debug"
    )
